package com.jd.header;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MP4Activity extends AppCompatActivity implements View.OnClickListener {

    private VideoView videoView;
    private LinearLayout layoutProgress;
    private TextView tvProgress;
    private ImageView imgPlay;
    private SeekBar seekBar;
    private TextView tvPlayProgress;
    private ImageView imgBack;
    private ImageView imgVolume;
    private SeekBar seekBarVolume;
    private boolean isPlay = false;
    private Handler handlerTimer;
    private Handler handlerBuffer;

    private AudioManager audioManager = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        //设置状态栏文字颜色及图标为深色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
        setContentView(R.layout.activity_mp4);
        init();
        initLister();
    }

    private void init() {
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        imgBack = findViewById(R.id.imgBack);
        imgBack.setOnClickListener(this);
        layoutProgress = findViewById(R.id.layoutProgress);
        tvProgress = findViewById(R.id.tvProgress);
        videoView = findViewById(R.id.videoView);
        tvPlayProgress = findViewById(R.id.tvPlayProgress);
        seekBar = findViewById(R.id.seekBar);
        seekBarVolume = findViewById(R.id.seekBarVolume);
        imgPlay = findViewById(R.id.imgPlay);
        imgVolume = findViewById(R.id.imgVolume);
        imgPlay.setOnClickListener(this);
        imgVolume.setOnClickListener(this);

        String source1 = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4";
        startPlay(source1);

        setDefultVolume();
    }

    /**
     * 开始播放一个视频，上一集下一集可调用
     */
    private void startPlay(String playUrl) {

        isPlay = false;
        Uri uri = Uri.parse(playUrl);
        videoView.setVideoURI(uri);

        layoutProgress.setVisibility(View.VISIBLE);
        tvPlayProgress.setText("00:00/00:00");
        tvProgress.setText("正在缓冲 0%");

        if(handlerBuffer != null){
            handlerBuffer.removeCallbacksAndMessages(null);
            handlerBuffer = null;
        }

        handlerBuffer = new Handler();

        handlerBuffer.postDelayed(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                int bufferPercentage = videoView.getBufferPercentage();

                if (isPlay) {
                    imgPlay.setImageResource(R.mipmap.icon_play_start_mp4);
                } else {
                    imgPlay.setImageResource(R.mipmap.icon_play_end_mp4);
                }

                if (bufferPercentage < 100) {
                    if (bufferPercentage > 0 && videoView.getDuration() > 0) {
                        tvPlayProgress.setText("00:00/" + MediaPlayerManager.getInstance().postions(videoView.getDuration()));
                    }
                    tvProgress.setText("正在缓冲 " + bufferPercentage + "%");
                    handlerBuffer.postDelayed(this, 500);
                } else {
                    isPlay = true;
                    seekBar.setMax(videoView.getDuration() / 1000);
                    tvPlayProgress.setText("00:00/" + MediaPlayerManager.getInstance().postions(videoView.getDuration()));
                    startPlayProgress();
                    layoutProgress.setVisibility(View.GONE);
                    imgPlay.setImageResource(R.mipmap.icon_play_start_mp4);
                    log("缓冲完成 100%");
                }
            }
        }, 500);

        videoView.start();
    }

    private void initLister() {

        /**
         * 准备就绪，即缓冲一部分或缓冲完成
         */
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                log("播放器准备就绪 开始播放 ");
            }
        });

        /**
         * 播放完成
         */
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onCompletion(MediaPlayer mp) {
                log("播放结束");
                isPlay = false;
                imgPlay.setImageResource(R.mipmap.icon_play_end_mp4);
                tvPlayProgress.setText(MediaPlayerManager.getInstance().postions(videoView.getDuration()) +
                        "/" + MediaPlayerManager.getInstance().postions(videoView.getDuration()));
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                Toast.makeText(MP4Activity.this, "播放错误", Toast.LENGTH_SHORT).show();
                return false;
            }
        });

        /**
         * 视频播放进度监听控制
         */
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvPlayProgress.setText(MediaPlayerManager.getInstance().postions(videoView.getCurrentPosition())
                        + "/" + MediaPlayerManager.getInstance().postions(videoView.getDuration()));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                if (videoView != null && videoView.isPlaying()) {
                    videoView.pause();
                }
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (videoView != null) {
                    if (seekBar.getProgress() < seekBar.getMax() && !isPlay) {
                        isPlay = true;
                    }
                    videoView.seekTo(seekBar.getProgress() * 1000);
                    videoView.start();
                }
            }
        });

        /**
         * 音量滑动监听
         */
        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                setStreamVolume(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    /**
     * 设置默认音量
     */
    private void setDefultVolume() {
        seekBarVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        seekBarVolume.setProgress(seekBarVolume.getMax() / 2);
        setStreamVolume(seekBarVolume.getMax() / 2);
    }

    /**
     * 设置指定音量
     *
     * @param index
     */
    public void setStreamVolume(int index) {
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, AudioManager.FLAG_PLAY_SOUND);
    }

    /**
     * 开始播放以后，启动监听进度，如果选集，需要重新调用
     */
    private void startPlayProgress() {
        if (handlerTimer != null) {
            handlerTimer.removeCallbacksAndMessages(null);
            handlerTimer = null;
        }
        handlerTimer = new Handler();

        handlerTimer.postDelayed(new Runnable() {
            @SuppressLint("SetTextI18n")
            @Override
            public void run() {
                if (isPlay) {
                    seekBar.setProgress(videoView.getCurrentPosition() / 1000);
                    tvPlayProgress.setText(MediaPlayerManager.getInstance().postions(videoView.getCurrentPosition()) +
                            "/" + MediaPlayerManager.getInstance().postions(videoView.getDuration()));
                }
                handlerTimer.postDelayed(this, 1000);
            }
        }, 1000);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.imgPlay) {
            if (isPlay) {
                videoView.pause();
                imgPlay.setImageResource(R.mipmap.icon_play_end_mp4);
                isPlay = false;
            } else {
                if (videoView.getCurrentPosition() == videoView.getDuration() && videoView.getCurrentPosition() > 0) {
                    videoView.seekTo(0);
                }
                videoView.start();
                imgPlay.setImageResource(R.mipmap.icon_play_start_mp4);
                isPlay = true;
            }
        } else if (v.getId() == R.id.imgBack) {
            finish();
        } else if (v.getId() == R.id.imgVolume) {
            if (seekBarVolume.getVisibility() == View.GONE) {
                seekBarVolume.setVisibility(View.VISIBLE);
            } else {
                seekBarVolume.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoView.stopPlayback();
    }

    private void log(String msg) {
        Log.e(getClass().getSimpleName(), msg);
    }

}